import React, {useState} from 'react';
import {observer} from 'mobx-react';
import {IMainStore} from '../store/index';
import {login} from '../api/auth';
import * as CryptoJS from 'crypto-js';
import '../scss/login.scss';

interface LoginProps {
  store: IMainStore;
  onLogin: (username: string, password: string) => void;
}

const Login: React.FC<LoginProps> = observer(({store, onLogin}) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim() || !password.trim()) {
      setError('请输入用户名和密码');
      return;
    }

    // 验证用户名不能为空（去除空格后）
    if (!username.trim()) {
      setError('用户名不能为空');
      return;
    }

    setLoading(true);
    setError('');

    try {
      // 处理登录参数：用户名trim，密码MD5加密
      const loginParams = {
        username: username.trim(),
        password: CryptoJS.MD5(password).toString().toUpperCase(),
        sysCode: 'web_oem'
      };
      
      // 调用真实的登录API
      const response = await login(loginParams);
      
      if (response.code === 200) {
        // 登录成功
        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('user', JSON.stringify({
          username,
          role: 'admin',
          ...response.data?.user
        }));
        onLogin(username, password);
        // 登录成功后，store会自动更新状态，组件会重新渲染并跳转到主页面
      } else {
        setError(response.message || '登录失败');
      }
    } catch (err: any) {
      console.error('Login error:', err);
      setError(err.response?.data?.message || '登录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <div className="login-header">
          <h1>AMIS 编辑器</h1>
          <p>可视化编辑器登录</p>
        </div>
        
        <form onSubmit={handleSubmit} className="login-form">
          {error && <div className="error-message">{error}</div>}
          
          <div className="form-group">
            <label htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="请输入用户名"
              disabled={loading}
            />
          </div>
          
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入密码"
              disabled={loading}
            />
          </div>
          
          <button 
            type="submit" 
            className="login-button"
            disabled={loading}
          >
            {loading ? '登录中...' : '登录'}
          </button>
        </form>
        
        <div className="login-footer">
          <p>请输入您的用户名和密码</p>
          <p style={{fontSize: '10px', color: '#999'}}>密码将使用MD5加密传输</p>
        </div>
      </div>
    </div>
  );
});

export default Login; 